package com.atguigu.gulimail.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 感知异常，统一处理异常的类
 * ControllerAdvice(basePackages = "com.atguigu.product.controller")表示处理这个包里面出现的异常
 */
//以json方式传数据给浏览器
@ResponseBody
//表明需要处理哪里的异常
@ControllerAdvice(basePackages = "com.atguigu.gulimail.product.controller")
@Slf4j
public class GulimailExceptionControllerAdvice {

    /**
     * 精确匹配想要捕获的异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题", e.getMessage() + "异常类型" + e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Map<String,String> errorMap=new HashMap<>();
        for (int i = 0; i < fieldErrors.size(); i++) {
            String field = fieldErrors.get(i).getField();
            String defaultMessage = fieldErrors.get(i).getDefaultMessage();
            errorMap.put(field,defaultMessage);
        }
        //return R.error(400,"数据校验出现问题").put("data",errorMap);
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMessage()).put("data",errorMap);
    }

    /**
     * 感知到所有的异常
     * 如果没有捕获到具体的异常但是还是出现了异常就捕获最大的异常
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMessage());
    }
}
